package com.test.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * @ClassName: MutablePropertyValues
 * @description: 用来存储并管理多个PropertyValue对象
 * @author: Mr du
 * @create: 2024-04-08 22:20
 */
public class MutablePropertyValues implements Iterable<PropertyValue>{

    //定义list集合对象
    private final List<PropertyValue> propertyValues;

    public MutablePropertyValues() {
        this.propertyValues = new ArrayList<PropertyValue>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValues) {
        if (propertyValues == null) {
            this.propertyValues = new ArrayList<>();
        }else {
            this.propertyValues = propertyValues;
        }
    }

    //获取PropertyValue对象,返回PropertyValue数组
    public PropertyValue[] getPropertyValues(){
        //将集合转换为数组返回
        return propertyValues.toArray(new PropertyValue[propertyValues.size()]);
    }

    //根据name获取PropertyValue对象
    public PropertyValue getPropertyValue(String propertyName){
        for (PropertyValue propertyValue : this.propertyValues) {
            if (propertyValue.getName().equals(propertyName)) {
                return propertyValue;
            }
        }
        return null;
    }

    //判断集合是否为空
    public boolean isEmpty(){
        return this.propertyValues.isEmpty();
    }

    //判断是否有指定name属性值的对象
    public boolean contains(String propertyName){
        return this.getPropertyValue(propertyName)!=null;
    }


    //添加PropertyValue对象
    public MutablePropertyValues addPropertyValue(PropertyValue pv){
        //todo:严谨的做法是要校验异常的
        for (int i = 0; i < this.propertyValues.size(); i++) {
            //判断集合中存储PropertyValue对象是否和传递进来的重复
            PropertyValue propertyValue = this.propertyValues.get(i);
            if (propertyValue.getName().equals(pv.getName())){
                this.propertyValues.set(i, new PropertyValue(pv.getName(),pv.getRef(), pv.getValue()));
                return this;
            }
        }
        this.propertyValues.add(pv);
        return this;
    }

    //获取迭代器对象
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValues.iterator();
    }
}
